package graduation.project.mutant.strategy;

import graduation.project.body.Expression;
import graduation.project.body.Mutants;
import graduation.project.body.OriginExpression;
import graduation.project.exception.NonExpressionException;

import java.util.ArrayList;

public class DORFMutantsGen implements MutantsGenerator {

	public Mutants generateMutants(String expression, int mutantsNum) {
		
		try{
			OriginExpression originEx = new OriginExpression(expression);
			return generateMutants(originEx, mutantsNum);
		}catch(NonExpressionException e){
			System.out.println("DORFMutantsGen: the expression is invalid.");
			e.printStackTrace();
		}
		return null;
	}

	public Mutants generateMutants(OriginExpression originEx, int num) {
		
		int count = 0;
		Mutants result = new Mutants(originEx.getExpression(), "DORF");
		String idnf = originEx.getExpression();
		ArrayList<Expression> mutantSet = new ArrayList<Expression>();
		
		StringBuffer exp = new StringBuffer();
		exp.append(idnf);
		for(int i = 0; i < idnf.length(); i++){
			if(exp.charAt(i) == '!' || exp.charAt(i) == '+' || i == idnf.length() - 1 || exp.charAt(i + 1) == '+')
				continue;
			try {
				mutantSet.add(new Expression(exp.insert(i + 1, '+').toString()));
			} catch (NonExpressionException e) {
				System.out.println("DORFMutantsGen: the expression is invalid.");
				e.printStackTrace();
			}
			exp.deleteCharAt(i + 1);
			if(num != -1 && ++count >= num)
				break;
		}
		
		result.setMutants(mutantSet);
		return result;
	}

}
